package csvLoader

import csv.CsvParser;
import csvLoader.CsvLoaderService;
import db.DataDeleter;
import dump.DumpService;
import system.*;
import xml.*;
import app.*;




class CsvLoaderController {
	
//	CsvLoaderService csvLoaderService
	CsvParser csvParser
	
	DumpService dumpService = new DumpService();
	
	
	String path = Constants.csvFileDirectory;
	String ext = Constants.csvFileExt
	DataDeleter del = new DataDeleter();
	
	def csvLoad = {
		/*Backup db before import*/
		System.out.println(dumpService.backup())
		
		def filename = params.id //+ "." + ext
//		def file = new File( path + File.separatorChar +   filename )
		def filepath = path + filename 
		csvParser = new CsvParser(filepath)

		//		csvLoaderService.importData(path + filename);
		println(filepath)


		flash.message = "Database backed up and file "+filename+" imported";
		redirect( action:list )
	}

	def index = {
		redirect(action:list,params:params)
	}
	static transactional = true

	def allowedMethods = []

	def list = {
		def fileResourceInstanceList = []
		def f = new File(path)
		if( f.exists() ){
			f.eachFile(){ file->
				if( !file.isDirectory() )
					fileResourceInstanceList.add( file.name )
			}
		}
		fileResourceInstanceList = fileResourceInstanceList.sort()
		[ fileResourceInstanceList: fileResourceInstanceList ]
	}

	def delete = {
		def filename = params.id
//		def filename = params.id.replace('###', '.')
		def file = new File( path + File.separatorChar +   filename )
		file.delete()
		flash.message = "file ${filename} removed"
		redirect( action:list )
	}

	def upload = {
		def f = request.getFile('fileUpload')
		if(!f.empty) {
			flash.message = 'Your file has been uploaded'
			new File(path).mkdirs()
			f.transferTo( new File( path + File.separatorChar + f.getOriginalFilename() ) )
		}
		else {
			flash.message = 'file cannot be empty'
		}
		redirect( action:list)
	}
	
	def download = {
		def filename = params.id;
		def file = new File( path + File.separatorChar + filename );

		try {
			//download
			response.setContentType("application/octet-stream");
			//view
			//response.contentType = "text/plain";
			response.outputStream << file.text;
		}
		catch(Exception e) {
			println(e.message);
		}

		redirect( action:list )
		flash.message = 'file ${filename} downloaded';
	}

	def view = {
		def filename = params.id;
		def file = new File( path + File.separatorChar + filename + ".csv");
		println(filename)
		//download
		//response.setContentType("application/octet-stream");
		//view
		try
		{
			response.contentType = "text/plain";
			response.outputStream << file.text;
		}
		catch(Exception e)
		{
			println(e.message);
		}
//		redirect( action:list )
	}
	
	def deleteAll = {
		del.deleteAll();
		flash.message = 'All data removed'
		redirect( action:list)
	}


	
}
